package com.trm.student.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.trm.role.dao.RoleDao;
import com.trm.student.dao.StudentDao;
import com.trm.student.service.StudentService;

public class StudentServlet extends HttpServlet {

    private int pageSize = 10;

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        doPost(request, response);
    }

    /**
     * 默认Servlet方法
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String methodName = request.getParameter("action");
        // 默认方法，用户列表
        if ((methodName == null) || "".equals(methodName)) {
            String role = request.getParameter("role"); // 角色id
            String page = request.getParameter("page"); // 页码
            Integer iPage = 1;
            StudentDao studentDao = new StudentDao();
            if (page != null && !"".equals(page)) {
                iPage = Integer.valueOf(page);
            } else {
                page = "1";
            }
            // 获得列表数据
            StudentService stuService = new StudentService();
            List<Map<String, Object>> list = stuService.getUserListByRole(role, iPage, pageSize);
            // 获得用户数量
            int count = studentDao.getUserCountByRoleId(role);
            // 页数量
            int pageNumber = count / pageSize;
            if (count % pageSize > 0) {
                pageNumber++;
            }
            if (pageNumber == 0) {
                pageNumber = 1;
            }
            request.setAttribute("properties", stuService.getProperties());
            request.setAttribute("list", list);
            request.setAttribute("role1", role);
            request.setAttribute("page", page);
            request.setAttribute("pageNumber", pageNumber);
            try {
                request.getRequestDispatcher("/student.jsp").forward(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            }
        } else {
            try {
                Method method = this.getClass().getMethod(methodName, HttpServletRequest.class,
                        HttpServletResponse.class);
                method.invoke(this.getClass().newInstance(), request, response);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存用户信息
     * 
     * @param request
     * @param response
     */
    public void addStudent(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String[]> map = request.getParameterMap();
        StudentService studentService = new StudentService();
        int result = studentService.saveUser(map);
        /*
         * try { request.getRequestDispatcher("/ztree/countrySave.jsp").forward(request,
         * response); } catch (ServletException e) { // TODO Auto-generated catch block
         * e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch
         * block e.printStackTrace(); }
         */
        String url = "StudentServlet?role=" + map.get("role")[0];
        if ("self".equals(request.getParameter("type"))) {
            url = "StudentServlet?action=edit&role=" + map.get("role")[0] + "&id=" + map.get("id")[0] + "&type=self";
            String userAgent = request.getHeader("user-agent");
            if (userAgent.contains("Android")) {
                url = "IndexServlet?type=mobile";
            }
        }
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加信息页面
     * 
     * @param request
     * @param response
     */
    @SuppressWarnings("unchecked")
    public void add(HttpServletRequest request, HttpServletResponse response) {
        String role = request.getParameter("role");
        request.setAttribute("role", role);
        // 获得角色属性
        StudentService stuService = new StudentService();
        List<Map<String, Object>> list = stuService.getProperty(role);
        request.setAttribute("properties", list);
        try {
            request.getRequestDispatcher("/add.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 编辑页面
     * 
     * @param request
     * @param response
     */
    @SuppressWarnings("unchecked")
    public void edit(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        StudentDao studentDao = new StudentDao();
        Map<String, Object> student = null;
        Map<String, Object> user = (Map<String, Object>) request.getSession().getAttribute("user");
        if (id.equals(String.valueOf(user.get("id")))) {
            student = user;
        }
        student = studentDao.getUserById(id);
        String role = request.getParameter("role");
        request.setAttribute("role", role);
        request.setAttribute("student", student);
        request.setAttribute("type", request.getParameter("type"));
        // 获得角色属性
        StudentService stuService = new StudentService();
        List<Map<String, Object>> list = stuService.getProperty(role);
        request.setAttribute("properties", list);
        if ("self".equals(request.getParameter("type"))) {
            // 获得当前权限可查看角色
            HttpSession session = request.getSession();
            RoleDao roleDao = new RoleDao();
            Map<String, Object> roleMap = (Map<String, Object>) session.getAttribute("role");
            String right = roleMap.get("right").toString();
            request.setAttribute("right", right);
            List<Map<String, Object>> roleList = roleDao.getRightRoleList(right);
            request.setAttribute("roleList", roleList);
        }
        try {
            request.getRequestDispatcher("/add.jsp").forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除用户
     * 
     * @param request
     * @param response
     */
    public void deleteUser(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("id");
        String role = request.getParameter("role");
        StudentDao studentDao = new StudentDao();
        int result = studentDao.deleteUserById(id);
        try {
            response.sendRedirect("StudentServlet?role=" + role);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
